package com.muc.plugin.handler;

import com.muc.plugin.dao.MUCDao;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.MUCRole;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.openfire.muc.spi.LocalMUCRoom;
import org.jivesoftware.openfire.muc.spi.MultiUserChatServiceImpl;
import org.jivesoftware.util.WebManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;

import java.util.List;
import java.util.Map;

/**
 * <iq id='c8mMp-10' type='set'>
 *     <query xmlns='xls:muc-member-remove'>
 *         <!-- 此处用来区分是主动退群(quit)或被踢出群(kick) -->
 *         <opt>kick</opt>
 *         <userId>03516a7f8799749d7c53b6be9ffda365</userId>
 *         <roomId>116</roomId>
 *         <roomJid>admin</roomJid>
 *     </query>
 * </iq>
 * 主动离开/被踢出 群
 */
public class MUCMemberRemoveIQHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String MODULE_NAME = "remove member";

    private static final String NAME_SPACE = "xls:muc-member-remove";

    public MUCMemberRemoveIQHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    private static final Logger log = LoggerFactory.getLogger(MUCMemberRemoveIQHandler.class);

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }

    @Override
    public IQ handleIQ(IQ packet) {
        log.info("execute " + this.getClass().getName() + " method: handleIQ");
        IQ reply = IQ.createResultIQ(packet);

        Element iq = packet.getElement();
        Element query = iq.element("query");
        Element opt = query.element("opt");
        Element userId = query.element("userId");
        Element roomId = query.element("roomId");
        Element roomJid = query.element("roomJid");
        if (opt == null || userId == null || roomId == null || roomJid == null) {
            reply.setError(PacketError.Condition.item_not_found);
            return reply;
        }
        String type = opt.getText();
        String userName = userId.getText();
        String roomName = roomJid.getText();
        // 从openfire房间用户缓存中删除此用户
        XMPPServer server = XMPPServer.getInstance();
        JID jid = server.createJID(userId.getText(), null);
        List<Map<String, String>> data = MUCDao.getMUCInfo(jid.toBareJID());
        if (data != null && data.size() > 0) {
            Map<String, String> map = null;
            for (int i = 0, len = data.size(); i < len; i++) {
                map = data.get(i);
                String serviceID = map.get("serviceID");
                String currRoomId = map.get("roomid");
                if (currRoomId.equals(roomId)) {
                    MultiUserChatServiceImpl mucService = (MultiUserChatServiceImpl) server
                            .getMultiUserChatManager().getMultiUserChatService(Long.parseLong(serviceID));
                    LocalMUCRoom localMUCRoom = (LocalMUCRoom) mucService.getChatRoom(map.get("name"));
                    try {
                        // 添加为none时会删除members缓存中的此用户,以便下次加入时持久化此用户
                        localMUCRoom.addNone(jid, localMUCRoom.getRole());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        MUCRoom room = new WebManager().getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(roomName);
        // 如果用户在线,就主动离开/踢出
        if (room.hasOccupant(userName)) {
            try {
                MUCRole role = room.getOccupant(userName);
                // 主动离开
                if (type.equals("quit")) {
                    // 客户端调用主动离开的方法,同时发起请求从数据表中删除自身数据
                    room.leaveRoom(role);
                }
                // 踢出
                else if (type.equals("kick")) {
                    room.kickOccupant(role.getUserAddress(), XMPPServer.getInstance().createJID(userName, null), null, "");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 从群昵称表中移除用户群昵称
        MUCDao.removeUserNickName(userName, roomName);
        reply.setType(IQ.Type.result);
        log.info("success result: " + reply.toXML());
        return reply;
    }


}
